<template>
  <div class="reservation-management">
    <div class="header">
      <h2>景点预约管理</h2>
      <div class="header-actions">
        <el-input
          v-model="searchQuery"
          placeholder="搜索用户姓名、联系电话"
          style="width: 250px; margin-right: 16px"
          clearable
        />
        <!-- <el-button type="success" @click="handleExport" :loading="exportLoading">
          <el-icon><Download /></el-icon>
          导出Excel
        </el-button> -->
        <el-button type="primary" @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="statistics">
      <el-row :gutter="16">
        <el-col :span="4">
          <div class="stat-card">
            <div class="stat-label">总预约数</div>
            <div class="stat-number">{{ totalReservations }}</div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="stat-card">
            <div class="stat-label">已选择</div>
            <div class="stat-number">{{ selectedReservations.length }}</div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <el-row :gutter="16">
        <el-col :span="4">
          <el-select
            v-model="filterForm.status"
            placeholder="预约状态"
            clearable
            style="width: 100%"
          >
            <el-option label="待确认" value="pending" />
            <el-option label="已确认" value="confirmed" />
            <el-option label="已取消" value="cancelled" />
            <el-option label="已完成" value="completed" />
            <el-option label="已过期" value="expired" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-col>
        <el-col :span="11">
          <el-button type="primary" @click="handleFilter">
            <el-icon><Search /></el-icon>
            筛选
          </el-button>
          <el-button @click="handleResetFilter">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button
            type="success"
            @click="handleBatchConfirm"
            :disabled="selectedReservations.length === 0"
          >
            <el-icon><Check /></el-icon>
            批量确认
          </el-button>
          <el-button
            type="warning"
            @click="handleBatchCancel"
            :disabled="selectedReservations.length === 0"
          >
            <el-icon><Close /></el-icon>
            批量取消
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 景点折叠面板 -->
    <div class="scenic-collapse-container" v-loading="loading">
      <el-collapse v-model="activeScenics" accordion>
        <el-collapse-item
          v-for="scenic in scenicSpots"
          :key="scenic.name"
          :title="`${scenic.name} (${scenic.reservations.length}个预约)`"
          :name="scenic.name"
        >
          <template #title>
            <div class="scenic-header">
              <span class="scenic-name">{{ scenic.name }}</span>
              <el-tag type="info" size="small"
                >{{ scenic.reservations.length }}个预约</el-tag
              >
            </div>
          </template>

          <!-- 景点下的预约列表 -->
          <el-table
            :data="scenic.reservations"
            style="width: 100%"
            stripe
            border
            size="small"
            :header-cell-style="{ background: '#f8f9fa', color: '#606266' }"
            @selection-change="
              (selection) => handleSelectionChange(selection, scenic.name)
            "
          >
            <el-table-column type="selection" width="55" />

            <el-table-column prop="id" label="预约ID" width="80" />

            <el-table-column prop="userName" label="用户姓名" width="120">
              <template #default="scope">
                <div class="user-cell">
                  <el-avatar :size="24" :src="scope.row.userAvatar">
                    <el-icon><User /></el-icon>
                  </el-avatar>
                  <span class="user-name">{{ scope.row.userName }}</span>
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="phone" label="联系电话" width="130" />

            <el-table-column prop="visitDate" label="预约日期" width="110" />

            <!-- <el-table-column prop="visitTime" label="时间段" width="140">
              <template #default="scope">
                <el-tag size="small" type="info">{{ scope.row.visitTime }}</el-tag>
              </template>
            </el-table-column> -->

            <el-table-column
              prop="peopleCount"
              label="人数"
              width="80"
              align="center"
            >
              <template #default="scope">
                <el-tag
                  size="small"
                  :type="scope.row.peopleCount > 1 ? 'warning' : 'primary'"
                >
                  {{ scope.row.peopleCount }}人
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column label="状态" width="120">
              <template #default="scope">
                <el-tag :type="getStatusTagType(scope.row.status)" size="small">
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column prop="createTime" label="订单创建时间" width="160">
              <template #default="scope">
                <span>{{ formatDate(scope.row.createTime) }}</span>
              </template>
            </el-table-column>

            <el-table-column label="操作" width="200" fixed="right">
              <template #default="scope">
                <div class="action-buttons">
                  <el-button
                    type="primary"
                    size="small"
                    @click="handleViewDetail(scope.row)"
                    :icon="View"
                  >
                    查看
                  </el-button>
                  <el-dropdown
                    @command="(command) => handleAction(command, scope.row)"
                  >
                    <el-button size="small" type="info">
                      更多<el-icon class="el-icon--right"
                        ><arrow-down
                      /></el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item
                          command="confirm"
                          v-if="scope.row.status === 'pending'"
                        >
                          <el-icon><Check /></el-icon>确认预约
                        </el-dropdown-item>
                        <el-dropdown-item
                          command="cancel"
                          v-if="
                            ['pending', 'confirmed'].includes(scope.row.status)
                          "
                        >
                          <el-icon><Close /></el-icon>取消预约
                        </el-dropdown-item>
                        <el-dropdown-item
                          command="complete"
                          v-if="scope.row.status === 'confirmed'"
                        >
                          <el-icon><CircleCheck /></el-icon>标记完成
                        </el-dropdown-item>
                        <el-dropdown-item command="edit">
                          <el-icon><Edit /></el-icon>编辑预约
                        </el-dropdown-item>
                        <el-dropdown-item command="delete" divided>
                          <el-icon><Delete /></el-icon>删除记录
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
    </div>

    <!-- 预约详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="预约详情"
      width="800px"
      :top="'3%'"
      :close-on-click-modal="false"
    >
      <div v-if="currentReservation" class="reservation-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="预约ID">{{
            currentReservation.id
          }}</el-descriptions-item>
          <el-descriptions-item label="预约状态">
            <el-tag :type="getStatusTagType(currentReservation.status)">
              {{ getStatusText(currentReservation.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="主预约人">{{
            currentReservation.userName
          }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{
            currentReservation.phone
          }}</el-descriptions-item>
          <el-descriptions-item label="身份证号">{{
            currentReservation.idCard || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="邮箱地址">{{
            currentReservation.email || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="景点名称" :span="2">{{
            currentReservation.scenicSpot
          }}</el-descriptions-item>
          <el-descriptions-item label="预约日期">{{
            currentReservation.visitDate
          }}</el-descriptions-item>
          <!-- <el-descriptions-item label="时间段">{{ currentReservation.visitTime }}</el-descriptions-item> -->
          <el-descriptions-item label="预约人数"
            >{{ currentReservation.peopleCount }}人</el-descriptions-item
          >
          <el-descriptions-item label="票价类型">{{
            currentReservation.ticketType || "成人票"
          }}</el-descriptions-item>
          <el-descriptions-item label="总金额">
            <span class="price"
              >¥{{ currentReservation.totalAmount || 0 }}</span
            >
          </el-descriptions-item>
          <el-descriptions-item label="支付状态">
            <el-tag
              :type="
                currentReservation.paymentStatus === 'paid'
                  ? 'success'
                  : 'warning'
              "
            >
              {{
                currentReservation.paymentStatus === "paid"
                  ? "已支付"
                  : "未支付"
              }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="预约时间" :span="2">{{
            formatDate(currentReservation.createTime)
          }}</el-descriptions-item>
          <el-descriptions-item label="操作人员">{{
            currentReservation.operator || "-"
          }}</el-descriptions-item>
          <el-descriptions-item label="最后更新">{{
            formatDate(currentReservation.updateTime)
          }}</el-descriptions-item>
          <el-descriptions-item label="备注信息" :span="2">
            {{ currentReservation.remarks || "无" }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 代预约游客信息 -->
        <div
          v-if="
            currentReservation.peopleCount > 1 && currentReservation.companions
          "
          class="companions-info"
        >
          <h4>代预约游客信息</h4>
          <el-table
            :data="currentReservation.companions"
            border
            size="small"
            style="margin-top: 10px"
          >
            <el-table-column prop="name" label="姓名" width="120" />
            <el-table-column prop="idCard" label="身份证号" width="200" />
            <el-table-column prop="phone" label="联系电话" width="130" />
          </el-table>
        </div>

        <!-- 操作日志 -->
        <div
          class="operation-log"
          v-if="
            currentReservation.operationLog &&
            currentReservation.operationLog.length > 0
          "
        >
          <h4>操作日志</h4>
          <el-timeline>
            <el-timeline-item
              v-for="log in currentReservation.operationLog"
              :key="log.id"
              :timestamp="formatDate(log.time)"
              placement="top"
            >
              <div class="log-content">
                <span class="log-action">{{ log.action }}</span>
                <span class="log-operator">操作人：{{ log.operator }}</span>
                <div v-if="log.remarks" class="log-remarks">
                  {{ log.remarks }}
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button
            v-if="currentReservation && currentReservation.status === 'pending'"
            type="success"
            @click="handleConfirm(currentReservation)"
          >
            确认预约
          </el-button>
          <el-button
            v-if="
              currentReservation &&
              ['pending', 'confirmed'].includes(currentReservation.status)
            "
            type="warning"
            @click="handleCancel(currentReservation)"
          >
            取消预约
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑预约对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑预约"
      width="800px"
      :top="'3%'"
      :close-on-click-modal="false"
    >
      <el-form
        v-if="editForm"
        :model="editForm"
        label-width="120px"
        :rules="editRules"
        ref="editFormRef"
      >
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="主预约人姓名" prop="userName">
              <el-input
                v-model="editForm.userName"
                placeholder="请输入用户姓名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="editForm.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input
                v-model="editForm.idCard"
                placeholder="请输入身份证号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱地址">
              <el-input
                v-model="editForm.email"
                placeholder="请输入邮箱地址（可选）"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="景点名称" prop="scenicSpot">
              <el-select v-model="editForm.scenicSpot" style="width: 100%">
                <el-option label="三坊七巷" value="三坊七巷" />
                <el-option label="鼓山风景区" value="鼓山风景区" />
                <el-option label="西湖公园" value="西湖公园" />
                <el-option
                  label="马尾船政文化博物馆"
                  value="马尾船政文化博物馆"
                />
                <el-option label="福州国家森林公园" value="福州国家森林公园" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预约日期" prop="visitDate">
              <el-date-picker
                v-model="editForm.visitDate"
                type="date"
                placeholder="选择预约日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <!-- <el-col :span="12">
            <el-form-item label="时间段" prop="visitTime">
              <el-select v-model="editForm.visitTime" style="width: 100%">
                <el-option label="上午 09:00-12:00" value="上午 09:00-12:00" />
                <el-option label="下午 13:00-17:00" value="下午 13:00-17:00" />
                <el-option label="全天 09:00-17:00" value="全天 09:00-17:00" />
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="预约人数" prop="peopleCount">
              <el-input-number
                v-model="editForm.peopleCount"
                :min="1"
                :max="20"
                style="width: 100%"
                @change="handlePeopleCountChange"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 代预约游客信息 -->
        <div v-if="editForm.peopleCount > 1" class="companions-section">
          <el-divider content-position="left">代预约游客信息</el-divider>
          <div
            v-for="(companion, index) in editForm.companions"
            :key="index"
            class="companion-item"
          >
            <h5>游客{{ index + 1 }}</h5>
            <el-row :gutter="16">
              <el-col :span="12">
                <el-form-item
                  :label="`姓名`"
                  :prop="`companions.${index}.name`"
                  :rules="[
                    { required: true, message: '请输入姓名', trigger: 'blur' },
                  ]"
                >
                  <el-input v-model="companion.name" placeholder="请输入姓名" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  :label="`身份证号`"
                  :prop="`companions.${index}.idCard`"
                  :rules="[
                    {
                      required: true,
                      message: '请输入身份证号',
                      trigger: 'blur',
                    },
                  ]"
                >
                  <el-input
                    v-model="companion.idCard"
                    placeholder="请输入身份证号"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  :label="`联系电话`"
                  :prop="`companions.${index}.phone`"
                  :rules="[
                    {
                      required: true,
                      message: '请输入联系电话',
                      trigger: 'blur',
                    },
                  ]"
                >
                  <el-input
                    v-model="companion.phone"
                    placeholder="请输入联系电话"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <!-- <el-row>
              <el-col :span="12">
                <el-form-item :label="`与主预约人关系`">
                  <el-select v-model="companion.relation" style="width: 100%" placeholder="请选择关系">
                    <el-option label="配偶" value="配偶" />
                    <el-option label="子女" value="子女" />
                    <el-option label="父母" value="父母" />
                    <el-option label="朋友" value="朋友" />
                    <el-option label="同事" value="同事" />
                    <el-option label="其他" value="其他" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row> -->
          </div>
        </div>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="预约状态">
              <el-select v-model="editForm.status" style="width: 100%">
                <el-option label="待确认" value="pending" />
                <el-option label="已确认" value="confirmed" />
                <el-option label="已取消" value="cancelled" />
                <el-option label="已完成" value="completed" />
                <el-option label="已过期" value="expired" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="票价类型">
              <el-select v-model="editForm.ticketType" style="width: 100%">
                <el-option label="成人票" value="成人票" />
                <el-option label="学生票" value="学生票" />
                <el-option label="儿童票" value="儿童票" />
                <el-option label="老人票" value="老人票" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注信息">
          <el-input
            v-model="editForm.remarks"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleSaveEdit"
            :loading="editLoading"
          >
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 状态变更确认对话框 -->
    <el-dialog
      v-model="statusDialogVisible"
      title="状态变更确认"
      width="500px"
      :top="'3%'"
    >
      <el-form :model="statusForm" label-width="80px">
        <el-form-item label="变更动作">
          <el-tag
            :type="statusForm.action === 'confirm' ? 'success' : 'warning'"
          >
            {{ statusForm.actionText }}
          </el-tag>
        </el-form-item>
        <el-form-item label="操作理由">
          <el-input
            v-model="statusForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入操作理由（可选）"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="statusDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="confirmStatusChange"
            :loading="statusLoading"
          >
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Refresh,
  Search,
  Check,
  Close,
  Delete,
  View,
  User,
  Download,
  ArrowDown,
  Edit,
  CircleCheck,
} from "@element-plus/icons-vue";

// 响应式数据
const loading = ref(false);
const exportLoading = ref(false);
const editLoading = ref(false);
const statusLoading = ref(false);
const searchQuery = ref("");
const currentPage = ref(1);
const pageSize = ref(20);
const totalReservations = ref(0);
const detailDialogVisible = ref(false);
const editDialogVisible = ref(false);
const statusDialogVisible = ref(false);
const currentReservation = ref(null);
const selectedReservations = ref([]);
const editForm = ref(null);
const editFormRef = ref(null);
const activeScenics = ref([]);

// 筛选表单
const filterForm = reactive({
  status: "",
  scenicSpot: "",
  dateRange: [],
});

// 状态变更表单
const statusForm = reactive({
  action: "",
  actionText: "",
  reason: "",
  reservationIds: [],
});

// 编辑表单验证规则
const editRules = {
  userName: [
    { required: true, message: "请输入用户姓名", trigger: "blur" },
    { min: 2, max: 20, message: "姓名长度在 2 到 20 个字符", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  scenicSpot: [{ required: true, message: "请选择景点", trigger: "change" }],
  visitDate: [{ required: true, message: "请选择预约日期", trigger: "change" }],
  peopleCount: [{ required: true, message: "请输入预约人数", trigger: "blur" }],
};

// 预约数据
const reservations = ref([
  {
    id: 1,
    userName: "张三",
    userAvatar:
      "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
    phone: "13800138001",
    idCard: "350100199001011234",
    email: "zhangsan@example.com",
    scenicSpot: "三坊七巷",
    visitDate: "2024-04-15",
    visitTime: "上午 09:00-12:00",
    peopleCount: 3,
    ticketType: "成人票",
    totalAmount: 90,
    paymentStatus: "paid",
    status: "confirmed",
    remarks: "希望安排导游服务",
    createTime: "2024-04-10 14:30:00",
    updateTime: "2024-04-10 15:20:00",
    operator: "管理员A",
    companions: [
      {
        name: "李梅",
        idCard: "350100199002021234",
        phone: "13800138002",
        relation: "配偶",
      },
      {
        name: "张小明",
        idCard: "350100201501011234",
        phone: "13800138003",
        relation: "子女",
      },
    ],
    operationLog: [
      {
        id: 1,
        action: "预约创建",
        operator: "系统",
        time: "2024-04-10 14:30:00",
        remarks: "用户在线预约",
      },
      {
        id: 2,
        action: "预约确认",
        operator: "管理员A",
        time: "2024-04-10 15:20:00",
        remarks: "审核通过，预约确认",
      },
    ],
  },
  {
    id: 2,
    userName: "李四",
    userAvatar:
      "https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png",
    phone: "13900139002",
    idCard: "350200199002022345",
    email: "lisi@example.com",
    scenicSpot: "鼓山风景区",
    visitDate: "2024-04-16",
    visitTime: "全天 09:00-17:00",
    peopleCount: 4,
    ticketType: "成人票",
    totalAmount: 120,
    paymentStatus: "unpaid",
    status: "pending",
    remarks: "",
    createTime: "2024-04-11 09:15:00",
    updateTime: "2024-04-11 09:15:00",
    operator: null,
    companions: [
      {
        name: "王芳",
        idCard: "350200199003032345",
        phone: "13900139003",
        relation: "朋友",
      },
      {
        name: "赵强",
        idCard: "350200199004042345",
        phone: "13900139004",
        relation: "朋友",
      },
      {
        name: "孙丽",
        idCard: "350200199005052345",
        phone: "13900139005",
        relation: "朋友",
      },
    ],
    operationLog: [
      {
        id: 1,
        action: "预约创建",
        operator: "系统",
        time: "2024-04-11 09:15:00",
        remarks: "用户在线预约",
      },
    ],
  },
  {
    id: 3,
    userName: "王五",
    userAvatar: "",
    phone: "13700137003",
    idCard: "350300199003033456",
    email: null,
    scenicSpot: "西湖公园",
    visitDate: "2024-04-17",
    visitTime: "下午 13:00-17:00",
    peopleCount: 1,
    ticketType: "学生票",
    totalAmount: 15,
    paymentStatus: "paid",
    status: "completed",
    remarks: "学生证已验证",
    createTime: "2024-04-08 16:45:00",
    updateTime: "2024-04-17 18:00:00",
    operator: "管理员B",
    companions: [],
    operationLog: [
      {
        id: 1,
        action: "预约创建",
        operator: "系统",
        time: "2024-04-08 16:45:00",
        remarks: "用户在线预约",
      },
      {
        id: 2,
        action: "预约确认",
        operator: "管理员B",
        time: "2024-04-08 17:00:00",
        remarks: "学生证验证通过",
      },
      {
        id: 3,
        action: "预约完成",
        operator: "管理员B",
        time: "2024-04-17 18:00:00",
        remarks: "用户已完成游览",
      },
    ],
  },
  {
    id: 4,
    userName: "赵六",
    userAvatar:
      "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
    phone: "13600136004",
    idCard: "350400199004044567",
    email: "zhaoliu@example.com",
    scenicSpot: "马尾船政文化博物馆",
    visitDate: "2024-04-18",
    visitTime: "上午 09:00-12:00",
    peopleCount: 2,
    ticketType: "成人票",
    totalAmount: 60,
    paymentStatus: "paid",
    status: "cancelled",
    remarks: "因天气原因取消",
    createTime: "2024-04-12 11:20:00",
    updateTime: "2024-04-13 10:30:00",
    operator: "管理员A",
    companions: [
      {
        name: "钱七",
        idCard: "350400199005054567",
        phone: "13600136005",
        relation: "朋友",
      },
    ],
    operationLog: [
      {
        id: 1,
        action: "预约创建",
        operator: "系统",
        time: "2024-04-12 11:20:00",
        remarks: "用户在线预约",
      },
      {
        id: 2,
        action: "预约确认",
        operator: "管理员A",
        time: "2024-04-12 14:00:00",
        remarks: "预约确认",
      },
      {
        id: 3,
        action: "预约取消",
        operator: "管理员A",
        time: "2024-04-13 10:30:00",
        remarks: "因天气原因取消，已退款",
      },
    ],
  },
  {
    id: 5,
    userName: "孙七",
    userAvatar: "",
    phone: "13500135005",
    idCard: "350500199005055678",
    email: "sunqi@example.com",
    scenicSpot: "福州国家森林公园",
    visitDate: "2024-04-20",
    visitTime: "全天 09:00-17:00",
    peopleCount: 1,
    ticketType: "成人票",
    totalAmount: 30,
    paymentStatus: "paid",
    status: "expired",
    remarks: "个人预约",
    createTime: "2024-04-05 13:10:00",
    updateTime: "2024-04-20 18:00:00",
    operator: "系统",
    companions: [],
    operationLog: [
      {
        id: 1,
        action: "预约创建",
        operator: "系统",
        time: "2024-04-05 13:10:00",
        remarks: "用户在线预约",
      },
      {
        id: 2,
        action: "预约确认",
        operator: "管理员B",
        time: "2024-04-05 15:30:00",
        remarks: "个人预约确认",
      },
      {
        id: 3,
        action: "预约过期",
        operator: "系统",
        time: "2024-04-20 18:00:00",
        remarks: "用户未按时到达，预约自动过期",
      },
    ],
  },
  {
    id: 6,
    userName: "周八",
    userAvatar:
      "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
    phone: "13400134006",
    idCard: "350600199006066789",
    email: "zhouba@example.com",
    scenicSpot: "三坊七巷",
    visitDate: "2024-04-22",
    visitTime: "下午 13:00-17:00",
    peopleCount: 5,
    ticketType: "成人票",
    totalAmount: 150,
    paymentStatus: "paid",
    status: "confirmed",
    remarks: "家庭出游",
    createTime: "2024-04-15 10:20:00",
    updateTime: "2024-04-15 11:30:00",
    operator: "管理员A",
    companions: [
      {
        name: "吴九",
        idCard: "350600199007076789",
        phone: "13400134007",
        relation: "配偶",
      },
      {
        name: "周小一",
        idCard: "350600201801016789",
        phone: "13400134008",
        relation: "子女",
      },
      {
        name: "周小二",
        idCard: "350600202001016789",
        phone: "13400134009",
        relation: "子女",
      },
      {
        name: "周老爷",
        idCard: "350600196501016789",
        phone: "13400134010",
        relation: "父母",
      },
    ],
    operationLog: [
      {
        id: 1,
        action: "预约创建",
        operator: "系统",
        time: "2024-04-15 10:20:00",
        remarks: "用户在线预约",
      },
      {
        id: 2,
        action: "预约确认",
        operator: "管理员A",
        time: "2024-04-15 11:30:00",
        remarks: "家庭预约确认",
      },
    ],
  },
]);

// 计算属性 - 过滤预约
const filteredReservations = computed(() => {
  let result = reservations.value;

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(
      (reservation) =>
        reservation.userName.toLowerCase().includes(query) ||
        reservation.phone.includes(query)
    );
  }

  // 状态过滤
  if (filterForm.status) {
    result = result.filter(
      (reservation) => reservation.status === filterForm.status
    );
  }

  // 日期范围过滤
  if (filterForm.dateRange && filterForm.dateRange.length === 2) {
    const [startDate, endDate] = filterForm.dateRange;
    result = result.filter((reservation) => {
      return (
        reservation.visitDate >= startDate && reservation.visitDate <= endDate
      );
    });
  }

  return result;
});

// 计算属性 - 按景点分组的预约数据
const scenicSpots = computed(() => {
  const spots = {};

  filteredReservations.value.forEach((reservation) => {
    const spotName = reservation.scenicSpot;
    if (!spots[spotName]) {
      spots[spotName] = {
        name: spotName,
        reservations: [],
      };
    }
    spots[spotName].reservations.push(reservation);
  });

  // 转换为数组并按预约数量排序
  return Object.values(spots).sort(
    (a, b) => b.reservations.length - a.reservations.length
  );
});

// 方法
const getStatusText = (status) => {
  const statusMap = {
    pending: "待确认",
    confirmed: "已确认",
    cancelled: "已取消",
    completed: "已完成",
    expired: "已过期",
  };
  return statusMap[status] || status;
};

const getStatusTagType = (status) => {
  const typeMap = {
    pending: "warning",
    confirmed: "success",
    cancelled: "danger",
    completed: "info",
    expired: "info",
  };
  return typeMap[status] || "info";
};

const formatDate = (dateString) => {
  if (!dateString) return "-";
  return new Date(dateString).toLocaleString("zh-CN");
};

const handleFilter = () => {
  currentPage.value = 1;
  ElMessage.success("筛选完成");
};

const handleResetFilter = () => {
  filterForm.status = "";
  filterForm.scenicSpot = "";
  filterForm.dateRange = [];
  searchQuery.value = "";
  currentPage.value = 1;
  ElMessage.success("筛选条件已重置");
};

const handleRefresh = () => {
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
    ElMessage.success("数据已刷新");
  }, 1000);
};

const handleSelectionChange = (selection, scenicName = null) => {
  if (scenicName) {
    // 景点特定的选择变更
    const newSelections = selection.map((item) => item.id);
    // 移除该景点之前的选择
    selectedReservations.value = selectedReservations.value.filter((id) => {
      const reservation = reservations.value.find((r) => r.id === id);
      return reservation && reservation.scenicSpot !== scenicName;
    });
    // 添加新选择
    selectedReservations.value.push(...newSelections);
  } else {
    selectedReservations.value = selection.map((item) => item.id);
  }
};

const handleViewDetail = (reservation) => {
  currentReservation.value = reservation;
  detailDialogVisible.value = true;
};

const handleAction = (command, reservation) => {
  switch (command) {
    case "confirm":
      handleConfirm(reservation);
      break;
    case "cancel":
      handleCancel(reservation);
      break;
    case "complete":
      handleComplete(reservation);
      break;
    case "edit":
      handleEdit(reservation);
      break;
    case "delete":
      handleDelete(reservation);
      break;
  }
};

const handleEdit = (reservation) => {
  editForm.value = {
    id: reservation.id,
    userName: reservation.userName,
    phone: reservation.phone,
    idCard: reservation.idCard,
    email: reservation.email || "",
    scenicSpot: reservation.scenicSpot,
    visitDate: reservation.visitDate,
    visitTime: reservation.visitTime,
    peopleCount: reservation.peopleCount,
    ticketType: reservation.ticketType || "成人票",
    status: reservation.status,
    remarks: reservation.remarks,
    companions: reservation.companions ? [...reservation.companions] : [],
  };
  editDialogVisible.value = true;
};

// 处理预约人数变更
const handlePeopleCountChange = (newCount) => {
  if (!editForm.value) return;

  const currentCompanions = editForm.value.companions || [];
  const companionsNeeded = newCount - 1; // 减去主预约人

  if (companionsNeeded > currentCompanions.length) {
    // 需要添加更多同伴
    const toAdd = companionsNeeded - currentCompanions.length;
    for (let i = 0; i < toAdd; i++) {
      currentCompanions.push({
        name: "",
        idCard: "",
        phone: "",
        relation: "",
      });
    }
  } else if (companionsNeeded < currentCompanions.length) {
    // 需要移除多余的同伴
    currentCompanions.splice(companionsNeeded);
  }

  editForm.value.companions = currentCompanions;
};

const handleSaveEdit = async () => {
  if (!editFormRef.value) return;

  try {
    await editFormRef.value.validate();
    editLoading.value = true;

    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 1000));

    // 更新预约数据
    const reservation = reservations.value.find(
      (r) => r.id === editForm.value.id
    );
    if (reservation) {
      Object.assign(reservation, {
        ...editForm.value,
        companions: editForm.value.companions || [],
      });
      reservation.updateTime = new Date().toLocaleString("zh-CN");
      reservation.operator = "当前管理员";

      // 添加操作日志
      reservation.operationLog.push({
        id: reservation.operationLog.length + 1,
        action: "预约修改",
        operator: "当前管理员",
        time: new Date().toLocaleString("zh-CN"),
        remarks: `预约信息已更新${
          editForm.value.peopleCount > 1 ? "，包含代预约游客信息" : ""
        }`,
      });
    }

    ElMessage.success("预约信息更新成功");
    editDialogVisible.value = false;
    editForm.value = null;
  } catch (error) {
    if (error !== false) {
      ElMessage.error("保存失败，请重试");
    }
  } finally {
    editLoading.value = false;
  }
};

const handleStatusChange = async (reservation, newStatus) => {
  const oldStatus = reservation.status;

  try {
    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 500));

    // 更新操作日志
    reservation.operationLog.push({
      id: reservation.operationLog.length + 1,
      action: `状态变更为${getStatusText(newStatus)}`,
      operator: "当前管理员",
      time: new Date().toLocaleString("zh-CN"),
      remarks: "通过下拉菜单直接修改",
    });

    reservation.updateTime = new Date().toLocaleString("zh-CN");
    reservation.operator = "当前管理员";

    ElMessage.success(`预约状态已更新为：${getStatusText(newStatus)}`);
  } catch (error) {
    // 如果更新失败，恢复原状态
    reservation.status = oldStatus;
    ElMessage.error("状态更新失败");
  }
};

const handleConfirm = (reservation) => {
  statusForm.action = "confirm";
  statusForm.actionText = "确认预约";
  statusForm.reservationIds = [reservation.id];
  statusForm.reason = "";
  statusDialogVisible.value = true;
};

const handleCancel = (reservation) => {
  statusForm.action = "cancel";
  statusForm.actionText = "取消预约";
  statusForm.reservationIds = [reservation.id];
  statusForm.reason = "";
  statusDialogVisible.value = true;
};

const handleComplete = async (reservation) => {
  try {
    await ElMessageBox.confirm(
      `确定要将预约 "${reservation.userName} - ${reservation.scenicSpot}" 标记为已完成吗？`,
      "确认操作",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info",
      }
    );

    reservation.status = "completed";
    reservation.updateTime = new Date().toLocaleString("zh-CN");
    reservation.operator = "当前管理员";

    // 添加操作日志
    reservation.operationLog.push({
      id: reservation.operationLog.length + 1,
      action: "预约完成",
      operator: "当前管理员",
      time: new Date().toLocaleString("zh-CN"),
      remarks: "管理员标记为已完成",
    });

    ElMessage.success("预约已标记为完成");
  } catch {
    ElMessage.info("已取消操作");
  }
};

const handleBatchConfirm = () => {
  if (selectedReservations.value.length === 0) {
    ElMessage.warning("请先选择要确认的预约");
    return;
  }
  statusForm.action = "confirm";
  statusForm.actionText = "批量确认预约";
  statusForm.reservationIds = [...selectedReservations.value];
  statusForm.reason = "";
  statusDialogVisible.value = true;
};

const handleBatchCancel = () => {
  if (selectedReservations.value.length === 0) {
    ElMessage.warning("请先选择要取消的预约");
    return;
  }
  statusForm.action = "cancel";
  statusForm.actionText = "批量取消预约";
  statusForm.reservationIds = [...selectedReservations.value];
  statusForm.reason = "";
  statusDialogVisible.value = true;
};

const confirmStatusChange = async () => {
  statusLoading.value = true;
  try {
    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 1000));

    // 更新预约状态
    statusForm.reservationIds.forEach((id) => {
      const reservation = reservations.value.find((r) => r.id === id);
      if (reservation) {
        reservation.status =
          statusForm.action === "confirm" ? "confirmed" : "cancelled";
        reservation.updateTime = new Date().toLocaleString("zh-CN");
        reservation.operator = "当前管理员";

        // 添加操作日志
        reservation.operationLog.push({
          id: reservation.operationLog.length + 1,
          action: statusForm.actionText,
          operator: "当前管理员",
          time: new Date().toLocaleString("zh-CN"),
          remarks: statusForm.reason || "批量操作",
        });
      }
    });

    const actionText = statusForm.action === "confirm" ? "确认" : "取消";
    ElMessage.success(
      `${statusForm.reservationIds.length}个预约已${actionText}`
    );

    statusDialogVisible.value = false;
    selectedReservations.value = [];
  } catch (error) {
    ElMessage.error("操作失败");
  } finally {
    statusLoading.value = false;
  }
};

const handleDelete = async (reservation) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除预约记录 "${reservation.userName} - ${reservation.scenicSpot}" 吗？此操作不可恢复。`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const index = reservations.value.findIndex((r) => r.id === reservation.id);
    if (index > -1) {
      reservations.value.splice(index, 1);
      ElMessage.success("删除成功");
    }
  } catch {
    ElMessage.info("已取消删除");
  }
};

// const handleExport = async () => {
//   exportLoading.value = true
//   try {
//     // 模拟导出Excel
//     await new Promise(resolve => setTimeout(resolve, 2000))

//     // 这里应该调用实际的导出API
//     ElMessage.success('Excel文件导出成功！')
//   } catch (error) {
//     ElMessage.error('导出失败，请重试')
//   } finally {
//     exportLoading.value = false
//   }
// }

const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 生命周期
onMounted(() => {
  totalReservations.value = reservations.value.length;
});
</script>

<style scoped>
.reservation-management {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.header h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  align-items: center;
  margin-left: auto;
  gap: 12px;
}

.filter-section {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

/* 景点折叠面板样式 */
.scenic-collapse-container {
  margin-bottom: 20px;
}

.scenic-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding-right: 20px;
}

.scenic-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.user-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-name {
  font-size: 13px;
  font-weight: 500;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

/* 统计信息样式 */
.statistics {
  margin-top: 20px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
}

.stat-card {
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12px;
  gap: 8px;
  background: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-number {
  line-height: 22px;
  vertical-align: middle;
  font-size: 22px;
  font-weight: 600;
  color: #409eff;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

/* 预约详情样式 */
.reservation-detail {
  max-height: 600px;
  overflow-y: auto;
}

.price {
  color: #f56c6c;
  font-weight: 600;
  font-size: 16px;
}

/* 代预约游客信息样式 */
.companions-info {
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
}

.companions-info h4 {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 16px;
}

/* 编辑表单中的代预约游客样式 */
.companions-section {
  margin-top: 20px;
}

.companion-item {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 4px solid #409eff;
}

.companion-item h5 {
  margin: 0 0 16px 0;
  color: #409eff;
  font-size: 14px;
  font-weight: 600;
}

.operation-log {
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
}

.operation-log h4 {
  margin: 0 0 16px 0;
  color: #303133;
}

.log-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.log-action {
  font-weight: 500;
  color: #409eff;
}

.log-operator {
  font-size: 12px;
  color: #909399;
}

.log-remarks {
  font-size: 12px;
  color: #606266;
  background: #f5f7fa;
  padding: 4px 8px;
  border-radius: 4px;
}

/* 折叠面板内表格样式 */
:deep(.el-collapse-item__content) {
  padding: 16px 20px;
  background: #fafafa;
}

:deep(.el-collapse-item__header) {
  padding: 0 20px;
  font-size: 16px;
  font-weight: 500;
}

:deep(.el-collapse-item__header.is-active) {
  color: #409eff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .header-actions {
    justify-content: space-between;
    margin-left: 0;
  }

  .filter-section .el-col {
    margin-bottom: 10px;
  }

  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }

  .scenic-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .companion-item .el-col {
    margin-bottom: 10px;
  }
}

/* 滚动条样式 */
.reservation-detail::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.reservation-detail::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.reservation-detail::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.reservation-detail::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 表格优化 */
:deep(.el-table) {
  border-radius: 6px;
  overflow: hidden;
}

:deep(.el-table th) {
  background: #f8f9fa !important;
}

:deep(.el-table--small .el-table__cell) {
  padding: 8px 0;
}
</style>
